package com.dream.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.util.ErrorHandler;

import java.util.concurrent.Executor;

/**
 * 调度器 和 异步任务执行器 线程池配置
 */
@Configuration
@EnableScheduling
@EnableAsync
public class AsyncSchedulerPoolConfig implements AsyncConfigurer, SchedulingConfigurer {

    private static final Logger log = LoggerFactory.getLogger(AsyncSchedulerPoolConfig.class);


    @Bean
    public ThreadPoolTaskScheduler getThreadPoolTaskScheduler() {
        ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
        scheduler.setPoolSize(200);
        scheduler.setAwaitTerminationSeconds(60);
        scheduler.setThreadNamePrefix("task-");
        scheduler.setErrorHandler(getTaskSchedulerErrorHandler());
        scheduler.setWaitForTasksToCompleteOnShutdown(true);
        return scheduler;
    }

    private ErrorHandler getTaskSchedulerErrorHandler(){
        return (throwable) -> {
            throwable.printStackTrace();
            log.error( "SchedulerErrorHandler : {}",throwable.toString());
        };
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (throwable, method, objects) -> {
            throwable.printStackTrace();
            log.error( "AsyncUncaughtExceptionHandler : {}",throwable.toString());
        };
    }

    @Override
    public void configureTasks(ScheduledTaskRegistrar registrar) {
        registrar.setTaskScheduler(getThreadPoolTaskScheduler());
    }


    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(20);
        executor.setMaxPoolSize(200);
        executor.setQueueCapacity(5000);
        executor.setThreadNamePrefix("async-");
        executor.initialize();
        return executor;
    }
}